package com.changhong.autopairservice.utils;

import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.os.Environment;
import android.util.Log;

import com.changhong.autopairservice.config.AotuPairConfig;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;


public class Common {
    public static String[] BLUETOOTH_NAMES = null;
    public static final int COMPLETE_NAME_FLAG = 9;
    public static final String CONFIG_PATH = "AutoPairConfig.xml";
    public static final String[] DEFAULT_MATCH_NAMES = new String[]{"YYYKQ", "IFLY_REMOTE", "CMCC_Voice_Remote", "BLE语音遥控器", "SW-Remote"};
    private static final String LOG_TAG = "AutoPair";
    private static final String LOG_FILE_NAME = "autopair_log.txt";

    //检查蓝牙名称
    public static boolean checkBluetoothName(String name) {
        if (BLUETOOTH_NAMES == null || BLUETOOTH_NAMES.length <= 0 || name == null) {
            return false;
        }
        String tempName = name.trim();
        for (String str : BLUETOOTH_NAMES) {
            if (tempName.contains(str.trim())) {
                return true;
            }
        }
        return false;
    }

    //比对/蓝牙名称相同
    public boolean compare(BluetoothDevice src, BluetoothDevice dst) {
        if (src == null || dst == null) {
            return false;
        }
        if (src == dst) {
            return true;
        }
        return src.getAddress().equals(dst.getAddress());
    }

    //支持BLE蓝牙检测
    public static boolean hasBLEFeature(Context context) {
        if (context.getPackageManager().hasSystemFeature("android.hardware.bluetooth_le")) {
            return true;
        }
        return false;
    }

    //
    public static boolean isMatchedHogpRecord(byte[] scanRecord) {
        if (scanRecord == null || scanRecord.length <= 0) {
            return false;
        }
        int length = scanRecord.length;
        int i = 0;
        byte[] RcName = new byte[50];
        String decodedName = null;
        while (i < length - 2) {
            int element_len = scanRecord[i];
            if (scanRecord[i + 1] == (byte) 9) {
                try {
                    System.arraycopy(scanRecord, i + 2, RcName, 0, element_len - 1);
                    decodedName = new String(RcName, "UTF-8");
                    Common.log("Common.isMatchedHogpRecord()-decodedName" + decodedName);

                    if (checkBluetoothName(decodedName)) {
                        return true;
                    }
                } catch (Exception e) {
                    Log.i(LOG_TAG, "error = " + e.toString());
                    e.printStackTrace();
                }

            } else {
            }
            i += element_len + 1;
        }
        return false;
    }

    public static AotuPairConfig loadConfig(Context context) {
        try {
            Serializer serializer = new Persister();
            // 先尝试从内部存储加载配置文件
            File configFile = new File(context.getFilesDir(), CONFIG_PATH);
            if (!configFile.exists()) {
                // 如果内部存储中没有配置文件，则从assets复制
                copyConfigFromAssets(context);
            }
            
            if (configFile.exists() && !configFile.isDirectory() && configFile.length() > 0) {
                return (AotuPairConfig) serializer.read(AotuPairConfig.class, configFile);
            } else {
                Common.log("Config file not found or invalid, using default config");
                return new AotuPairConfig();
            }
        } catch (Exception e) {
            Common.log("Failed to load config: " + e.getMessage());
            e.printStackTrace();
            return new AotuPairConfig();
        }
    }

    private static void copyConfigFromAssets(Context context) {
        try {
            InputStream inputStream = context.getAssets().open(CONFIG_PATH);
            File outFile = new File(context.getFilesDir(), CONFIG_PATH);
            java.io.FileOutputStream outputStream = new java.io.FileOutputStream(outFile);
            byte[] buffer = new byte[1024];
            int length;
            while ((length = inputStream.read(buffer)) > 0) {
                outputStream.write(buffer, 0, length);
            }
            inputStream.close();
            outputStream.close();
            Common.log("Config file copied from assets to internal storage");
        } catch (Exception e) {
            Common.log("Failed to copy config file from assets: " + e.getMessage());
            e.printStackTrace();
        }
    }

    public static boolean isEmpty(String content) {
        return content == null || content.trim().length() <= 0;
    }

    public static void log(String msg) {
        Log.d(LOG_TAG, msg);
        saveLogToFile(msg);
    }

    public static void log(BluetoothDevice device, String msg) {
        if (device == null) {
            log("device is null, " + msg);
            return;
        }
        // 将device.getAliasName()修改为device.getName()以提高兼容性
        log("[" + device.getName() + "] " + msg);
    }

    private static void saveLogToFile(String msg) {
        try {
            File logFile = new File(Environment.getExternalStorageDirectory(), LOG_FILE_NAME);
            FileOutputStream fos = new FileOutputStream(logFile, true);
            String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()).format(new Date());
            String logEntry = time + ": " + msg + "\n";
            fos.write(logEntry.getBytes());
            fos.close();
        } catch (IOException e) {
            Log.e(LOG_TAG, "Failed to save log to file: " + e.getMessage());
        }
    }
}